package com.rjwh.dingdong.client.widget;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.widget.EditText;

public class EmoticonsEditText extends EditText {

	public EmoticonsEditText(Context context) {
		super(context);
	}

	public EmoticonsEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public EmoticonsEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public void setText(CharSequence text, BufferType type) {
		if (!TextUtils.isEmpty(text)) {
			super.setText(replace(text.toString()), type);
		} else {
			super.setText(text, type);
		}
	}

	private Pattern buildPattern() {
		return Pattern.compile("\\[face_\\d{3}]", Pattern.CASE_INSENSITIVE);
	}

	private CharSequence replace(String text) {
		try {
			int imgSize = (int) getTextSize() + 5;
			SpannableString spannableString = new SpannableString(text);
			int start = 0;
			Pattern pattern = buildPattern();
			Matcher matcher = pattern.matcher(text);
			while (matcher.find()) {
				String faceText = matcher.group();
				String key = faceText.substring(1, faceText.length() - 1);
				MyImageSpan imageSpan = null;
				// 设置图片
				Drawable drawable = getResources().getDrawable(
						getContext().getResources().getIdentifier(key,
								"drawable", getContext().getPackageName()));
				drawable.setBounds(4, 4, imgSize, imgSize);
				imageSpan = new MyImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

				int startIndex = text.indexOf(faceText, start);
				int endIndex = startIndex + faceText.length();
				if (startIndex >= 0)
					spannableString.setSpan(imageSpan, startIndex, endIndex,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				start = (endIndex - 1);
			}
			return spannableString;
		} catch (Exception e) {
			return text;
		}
	}

	public class MyImageSpan extends ImageSpan {

		public MyImageSpan(Drawable drawable, int alignBaseline) {
			super(drawable);
		}

		@Override
		public void draw(Canvas canvas, CharSequence text, int start, int end,
				float x, int top, int y, int bottom, Paint paint) {
			Drawable b = getDrawable();
			canvas.save();
			int transY = 0;
			transY = ((bottom - top) - b.getBounds().bottom) / 2 + top;
			canvas.translate(x, transY);
			b.draw(canvas);
			canvas.restore();
		}
	}
}
